package com.blacksheep.mtm.service.Impl;

import com.blacksheep.mtm.common.exception.XmallException;
import com.blacksheep.mtm.common.exception.XmallUploadException;
import com.blacksheep.mtm.common.jedis.JedisClient;
import com.blacksheep.mtm.common.utils.FileUtil;
import com.blacksheep.mtm.common.utils.QiniuUtil;
import com.blacksheep.mtm.common.utils.ZxingOrCodeUtils;
import com.blacksheep.mtm.dao.TbDeviceMapper;
import com.blacksheep.mtm.dao.TbIceInMapper;
import com.blacksheep.mtm.pojo.common.DataTablesResult;
import com.blacksheep.mtm.pojo.manager.TbDevice;
import com.blacksheep.mtm.service.DeviceService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DeviceServiceImpl implements DeviceService {

    @Autowired
    private TbDeviceMapper tbDeviceMapper;

    @Autowired
    private JedisClient jedisClient;

    @Override
    public DataTablesResult getDeviceList(int draw, int start, int length, int[] state,String[] type, String search, String minDate, String maxDate, String orderCol, String orderDir) {
        DataTablesResult result=new DataTablesResult();
        PageHelper.startPage(start/length+1,length);
        List<TbDevice> list = tbDeviceMapper.selectList("%"+search+"%",state,type,minDate,maxDate,orderCol,orderDir);
        for (TbDevice device:list){
            if (StringUtils.equals("BBP",device.getType()) ||StringUtils.equals("LBP",device.getType()) ){
                if (jedisClient.exists("ICE_IN_TIME_"+device.getCode())){
                    String iceInTime = jedisClient.get("ICE_IN_TIME_"+device.getCode());
//                    Long iceInTime =Long.getLong(jedisClient.get("ICE_IN_TIME_"+device.getCode()));
                    if (iceInTime !=null){
                        long freezingTime = new Date().getTime() - Long.parseLong(iceInTime);
                        device.setFreezingTime(Math.round(freezingTime/3600/1000));
                    }
                }
            }
        }
        PageInfo<TbDevice> pageInfo=new PageInfo<>(list);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setDraw(draw);
        result.setData(list);
        return result;
    }

    @Override
    public DataTablesResult getWSDeviceList(int draw, int start, int length, int[] state, String search, String minDate, String maxDate, String orderCol, String orderDir) {
        DataTablesResult result=new DataTablesResult();
        PageHelper.startPage(start/length+1,length);
        List<TbDevice> list = tbDeviceMapper.selecWStList("%"+search+"%",state,minDate,maxDate,orderCol,orderDir);
        PageInfo<TbDevice> pageInfo=new PageInfo<>(list);
        result.setRecordsFiltered((int)pageInfo.getTotal());
        result.setDraw(draw);
        result.setData(list);
        return result;
    }

    @Override
    public TbDevice insert(TbDevice device) {
        String lastCode = tbDeviceMapper.selectLastCode(device.getType());
        int count = 1;
        if (!StringUtils.isBlank(lastCode)){
            count =Integer.parseInt(lastCode.substring(lastCode.length()-4))+1;
        }
        String code = formateCode(device.getType(),count);
        device.setCode(code);
        device.setQrcode(uploadImg(code));
        int result = tbDeviceMapper.insertSelective(device);
        if (result<1){
            throw new XmallException("新增失败");
        }
        return device;
    }

    @Override
    public TbDevice insertBatch(TbDevice device, int num) {
        String lastCode = tbDeviceMapper.selectLastCode(device.getType());
        int count = 1;
        if (!StringUtils.isBlank(lastCode)){
            count =Integer.parseInt(lastCode.substring(lastCode.length()-4))+1;
        }
        for (int i =0;i<num;i++){
            String code = formateCode(device.getType(),count);
            device.setCode(code);
            device.setQrcode(uploadImg(code));
            int result = tbDeviceMapper.insertSelective(device);
            if (result<1){
                throw new XmallException("新增失败");
            }
            count++;
        }
        return device;

    }

    @Override
    public TbDevice updateDevice(TbDevice device) {
        int result = tbDeviceMapper.updateByPrimaryKeySelective(device);
        if (result<1){
            throw new XmallException("更新失败");
        }
        return null;
    }

    @Override
    public TbDevice alertState(Integer id, Integer state) {
        int result = tbDeviceMapper.updateStateByPrimaryKey(id,state);
        if (result<1){
            throw new XmallException("更新失败");
        }
        return null;
    }

    @Override
    public int getDeviceCountByType(String type) {
        return 0;
    }

    @Override
    public List<String> getIceBoxList(String code) {
        return tbDeviceMapper.selectIceBoxCodeList('%'+code + '%');
    }

    @Override
    public void download(HttpServletResponse response) throws IOException{
        List<Map<String, Object>> list = new ArrayList<>();
        List<TbDevice> reulst = tbDeviceMapper.selectAllList();
        for (TbDevice device:reulst){
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("设备编码", device.getCode());
            map.put("设备类型", device.getType());
            map.put("设备新增时间", device.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);

    }

    private String formateCode(String type,int count){
        String code = type;
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        code=  code+ sdf.format(date) + String.format("%04d", count); ;
        return code;
    }

    private String uploadImg(String code){
        if (StringUtils.isBlank(code)){
            return null;
        }
        String qiniuPath = "";
        try {

            File path = new File("");
            File upload = new File(path.getAbsolutePath(),"upload/");
            if (!upload.exists()){
                upload.mkdirs();
            }
            File img  = new File(upload.getPath()+ UUID.randomUUID().toString()+".png");
ZxingOrCodeUtils.testEncode(code,img.getAbsolutePath(),true);
             qiniuPath =   QiniuUtil.qiniuUpload(img.getAbsolutePath());
            if (img.exists()){
                img.delete();
            }
            if(qiniuPath.contains("error")){
                throw new XmallException("上传失败");
            }
        }catch (WriterException ex){
            return null;
        }catch (IOException e){
            return null;
        }
        return qiniuPath;
    }


}
